package main

import (
	"cloud-disk/global"
	"cloud-disk/global/db"
	"cloud-disk/global/define"
	"cloud-disk/logic"
	"cloud-disk/mq"
	"cloud-disk/store"
	"encoding/json"
	"fmt"
	"log"
	"os"
)

func init() {
	global.Init("../config.yaml")
}

func ProcessTransfer(msg []byte) bool {
	fmt.Println("mq get message")
	transMsg := mq.TransferMessage{}
	err := json.Unmarshal(msg, &transMsg)
	if err != nil {
		log.Printf("fail to unmashal, err:%v\n", err.Error())
		return false
	}
	storeKey := transMsg.Prefix + "/" + transMsg.StoreKey
	//start := time.Now()
	err = store.ToOSS(transMsg.CurrLocation, storeKey)
	if err != nil {
		return false
	}
	//fmt.Printf("store to oss cost: %vs\n", time.Since(start).Seconds())
	// 更新数据库
	logic.UpdateFileStoreWayLogic(transMsg.FileHash, storeKey, "oss")
	return true
}

func ProcessRemoveChunk(msg []byte) bool {
	fmt.Println("mq get rm message")
	uploadId := string(msg)
	err := os.RemoveAll(uploadId)
	r := db.RDB().Get()
	defer r.Close()
	r.Do("del", "MPINFO_"+uploadId, "MPDONE_"+uploadId)

	if err != nil {
		log.Println(err)
		return false
	}
	fmt.Printf("rm %s/ success\n", string(msg))
	return true
}

func main() {
	conf := define.Conf.RabbitMQ
	done := make(chan struct{})
	go mq.StartConsumer(conf.TransferOssQueueName, "trans_oss", ProcessTransfer)
	go mq.StartConsumer(conf.RemoveChunkQueueName, "rm_chunk", ProcessRemoveChunk)

	<-done
}
